package com.restaurant.springboot.service.impl;

import com.restaurant.springboot.entity.CouponEntity;
import com.restaurant.springboot.entity.CouponEntityPK;
import com.restaurant.springboot.repositories.CouponRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@Service
public class CouponServiceImpl implements com.restaurant.springboot.service.CouponService {

    @Autowired
    private CouponRepository couponRepository;

    @Override
    public List<Map<String, Object>> getAllCouponByUserId(int userId){
        return couponRepository.findAllCouponByUserId(userId);
    }

    @Override
    @Transient
    public boolean useCoupon(int userId, int couponSeriesId){
        CouponEntity couponEntity = couponRepository.findById(new CouponEntityPK(userId,couponSeriesId)).get();
        if(couponEntity!=null){
            couponEntity.setUsed(true);
            if(couponRepository.save(couponEntity)!=null){
                return true;
            }
            return false;

        }
        return false;
    }

    @Override
    @Transient
    public boolean takeCoupon(int userId, int couponSeriesId, Timestamp receiveTime){
        CouponEntity couponEntity = new CouponEntity(userId,couponSeriesId,receiveTime,false);
        if(couponRepository.save(couponEntity)!=null){
            return true;
        }
        return false;
    }

    @Override
    public boolean isExistsCoupon(int userId, int couponSeriesId){
        return couponRepository.existsByUserIdAndCouponSeriesId(userId,couponSeriesId);
    }

    @Override
    @Transient
    public void deleteCoupon(int userId, int couponSeriesId){
        couponRepository.deleteByUserIdAndCouponSeriesId(userId,couponSeriesId);
    }

    @Override
    public CouponEntity getCoupon(int userId, int couponSeriesId){
        return couponRepository.findCouponEntityByUserIdAndCouponSeriesId(userId,couponSeriesId);
    }

    @Override
    public boolean updateCoupon(CouponEntity couponEntity){
        if(couponRepository.save(couponEntity)!=null){
            return true;
        }
        return false;
    }

    public boolean cancelOrderReturnCoupon(int userId,int couponSeriesId){
        CouponEntity couponEntity = couponRepository.findCouponEntityByUserIdAndCouponSeriesId(userId,couponSeriesId);
        couponEntity.setUsed(false);
        if(couponRepository.save(couponEntity)!=null){
            return true;
        }
        return false;
    }

}
